console.log('content script start')

// inject injected script
var s = document.createElement('script')
s.src = chrome.runtime.getURL('injected.js')
s.onload = function () {
    this.remove()
};
(document.head || document.documentElement).appendChild(s)
let data = []
// receive message from injected script
const myMap = new Map()
// 设置键值对
myMap.set('常州环球港邮轮酒店', '${userName}  ${roomType}-${mealType} ${startDate}  ${roomNum}${nightNum}  晨风旅行社 房价00000   房费预付，杂费自理，房价保密')
myMap.set('常州远洲酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  ')
myMap.set('茅山南湖度假庄园', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  ')
myMap.set('徐州吕梁水街开元颐居度假酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  00000')
myMap.set('常州沁悦大酒店（湖塘纺织城店）', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  00000')
myMap.set('常州都喜天丽富都青枫苑酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  00000')
myMap.set('常州宝丽格大酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  00000')
myMap.set('无锡鲁能万豪酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  ')
myMap.set('常州富都洲际酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  00000')
myMap.set('维也纳国际酒店（东莞松山湖店）', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  维也纳国际酒店（东莞松山湖店）')
myMap.set('茗静园·安吉禧玥山居度假酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  茗静园·安吉禧玥山居度假酒店')
myMap.set('建湖九龙国际大酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}   ${channel}')
myMap.set('南京国际会议大酒店', '客人：${userName}</br>入住：${startDate}</br>离店：${endDate}</br>房型：${roomType}</br>早餐：${mealType}</br>间数： ${roomNum}</br>金额：00000</br>渠道：${channel}')
myMap.set('都喜天丽富都长江龙城酒店', '${userName}  ${roomType} <${mealType}>  ${startDate}  ${roomNum}${nightNum}  ${channel} 00000 ')
myMap.set('茅山道温泉度假酒店', '预订信息</br>预订日期:${startDate}</br>预订业务员:美团合作</br>预订人:${userName}</br>预订房型:${roomType}</br>房间数量:${roomNum}${nightNum}</br>房费:00000/间</br>备注:')
myMap.set('瑞颐康养酒店', '酒店名 : 苏州瑞颐康养酒店</br>入离日期 : ${startDate}~${endDate}  共${nightNum}</br>客人姓名 :  ${userName}</br>预订房型 : ${roomType}-${roomNum} ${mealType}               </br>结算价：00000')
myMap.set('常州富都戴斯酒店', '店名 : 常州富都戴斯酒店</br>入离日期 :${startDate}至${endDate}共${nightNum}</br>客人姓名：${userName}</br>预订房型: ${roomType}房  ${mealType} ${roomNum}</br>结算价：00000</br>来源：${channel}</br>备注：该客人房费已支付，本公司统一结算。房价保密，杂费自理。</br>发票：本公司开具。</br>烦请确认回复，谢谢')
myMap.set('宝丽格大酒店', '${userName}  ${roomType}-${mealType} ${startDate}  ${roomNum}${nightNum}  00000')

var customDiv = null;
window.addEventListener('message',
    function (e) {
        const url = e.data.url;
        // const orgin = window.location.orgin;
        // console.log("window.location",window.location)
        /* if(!orgin){
         return
         }
         if(orgin.indexOf('me.meituan.com')<0 || url.indexOf("orders")<0){*/
        if (!url || (url.indexOf('orders/list') < 0&&url.indexOf('/orders/task/list') < 0 && !extractOrderIdFromUrl(url) && url.indexOf('sensitiveData') < 0)) {
            return
        }

        if (url.indexOf('orders/list') > -1||url.indexOf('/orders/task/list') > -1) {
            data = []
            let arr = JSON.parse(e.data.data).data.results
            if(!arr){
                arr = []
            }
            arr.forEach(function (row) {
                if (row.partRefundInfo == null) {
                    console.log(row, "row")
                }
                const userNames = row.guests.map(g => g.name).join(',');
                data.push({
                    orderId: row.orderId,
                    poiName: row.poiName,
                    userName: userNames,
                    startDate: row.checkInDateString.substring(0, 10),
                    endDate: row.checkOutDateString.substring(0, 10),
                    roomType: getRoomType(row.roomName),
                    mealType: getMealType(row.rpInfo),
                    roomNum: row.roomCount + '间',
                    nightNum: (row.checkInDateModels.length) + '晚',
                    channel: '美团'
                })
            })
        } else if (url.indexOf('sensitiveData') > -1) {
            const name = JSON.parse(e.data.data).data.sensitiveDataList[0].guestInfos.filter(g=>g.guestType === 'check_in_guest').map(g=>g.name).join(",")
            const regex = /(\d{19})/
            const match = url.match(regex)
            if (match) {
                const row = data.find(item => item.orderId === match[0])
                row.userName = name
            }
            renderDivs(data, myMap, customDiv, match[0])
            return
        } else if (!!extractOrderIdFromUrl(url)) {
            const orderId = extractOrderIdFromUrl(url)
            renderDivs(data, myMap, customDiv, orderId)
        }
        var buttons = document.querySelectorAll('button.my-button-class')
        console.log("按钮的数量", buttons.length)
        if (buttons.length == 0) {
            // 创建按钮
            var button = document.createElement('button')
            button.textContent = '打开弹框'
            button.style.position = 'fixed'
            button.style.top = '150px'
            button.style.right = '10px'
            button.style.zIndex = '999999999'
            button.style.padding = '10px'
            button.style.fontSize = '14px'
            button.style.backgroundColor = '#007BFF'
            button.style.color = 'white'
            button.style.border = 'none'
            button.style.borderRadius = '5px'
            button.style.cursor = 'pointer'
            button.classList.add('my-button-class')
            document.body.appendChild(button)
            // 创建自定义 div
            customDiv = document.createElement('div')
            customDiv.style.overflowY = 'auto'
            customDiv.style.display = 'none' // 初始时隐藏
            customDiv.style.position = 'fixed'
            customDiv.style.top = '200px'
            customDiv.style.right = '10px'
            customDiv.style.width = '450px'
            customDiv.style.padding = '20px'
            customDiv.style.backgroundColor = 'white' // 设置为白色
            customDiv.style.color = 'black'
            customDiv.style.borderRadius = '8px'
            customDiv.style.boxShadow = '0px 4px 8px rgba(0, 0, 0, 0.2)'
            customDiv.style.zIndex = '999999999999'
            customDiv.style.fontFamily = 'SimSun, 宋体, serif' // 设置字体为宋体
            customDiv.style.fontSize = '13px' // 设置字体大小为 11px
            customDiv.style.height = '200px'
            document.body.appendChild(customDiv)
            // 为按钮添加点击事件
            button.addEventListener('click',
                function () {
                    if (customDiv.style.display === 'none') {
                        // renderDivs(data, myMap, customDiv)
                        customDiv.style.display = 'block' // 如果 hidden，则显示 customDiv
                    } else {
                        customDiv.style.display = 'none' // 如果 visible，则隐藏 customDiv
                    }
                })
        }
        //console.log('content script received:', e.data.data);
    })

function extractOrderIdFromUrl(url) {
    const match = url.match(/\/orders\/(\d{19})(?=[\/?]|$)/);
    return match ? match[1] : null;
}

/**
 * 获取用餐类型
 * @param str
 * @returns String
 */
function getMealType(str) {
    const parts = str.split(/【|】/);
    const results = [];
    for (let i = 1; i < parts.length; i += 2) {
        results.push(parts[i]);
    }
    const mealType = results[0];
    if (mealType == '含2早') {
        return '双早'
    } else if (mealType == '含1早') {
        return '单早'
    }
    return mealType;
}


function renderDivs(data, myMap, customDiv, orderId) {
    // 删除 customDiv 中所有 class 为 'my-div-son' 的 div
    var sonDivs = customDiv.querySelectorAll('.my-div-son') // 获取所有 class 为 'my-div-son' 的 div
    sonDivs.forEach(function (div) {
        div.remove() // 删除每个 div
    })
    let i = 0
    const list = data.filter(row => row.orderId === orderId)
    list.forEach(function (div, index) {
        const string = myMap.get(div.poiName)
        if (!string) {
            return
        }
        i++;
        const result = string.replace('${userName}', div.userName)
            .replace('${roomType}', div.roomType)
            .replace('${mealType}', div.mealType)
            .replace('${startDate}', div.startDate)
            .replace('${endDate}', div.endDate)
            .replace('${roomNum}', div.roomNum)
            .replace('${nightNum}', div.nightNum)
            .replace('${channel}', div.channel)
        var div1 = document.createElement('div')
        if (i % 2 == 0) {
            div1.style.backgroundColor = 'lightgray'
        }
        //div1.innerHTML  = div.poiName+"      "+result; // 给第一个 div 添加文本内容
        div1.innerHTML = result // 给第一个 div 添加文本内容
        div1.classList.add('my-div-son')
        div1.style.marginBottom = '10px' // 给第一个 div 设置底部外边距
        customDiv.appendChild(div1)
        div1.addEventListener('click', function () {
            // 创建一个范围对象
            var range = document.createRange()
            range.selectNodeContents(div1)
            // 获取当前选择对象
            var selection = window.getSelection()
            selection.removeAllRanges()  // 清除任何现有的选择
            selection.addRange(range)    // 添加新的选择范围
        })
    })
}


function getRoomType(inputString) {
    // console.log('roomType',inputString)
    const roomRegex = /(.+?[房间屋])([ABCDE])?/;  // 匹配房型（如“豪华双人房”或“豪华大床间”）
    const roomMatch = inputString.match(roomRegex);  // 匹配房型

    return roomMatch ? roomMatch[1] : '';  // 如果匹配到，返回房型；否则返回空字符串
}
